package org.example.config;

import jakarta.annotation.Resource;
import org.example.exception.MyAuthenticationEntryPoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;


@EnableMethodSecurity // 开启方法级别的安全注解
@Configuration
public class SecurityConfiguration {

    @Resource
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;



    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(requests -> requests
                // 启动方法注解后，这里就不需要配置了
//                        .requestMatchers( "/product/list").hasAnyAuthority("PRODUCT_LIST")
//                        .requestMatchers( "/product/save").hasAnyAuthority("PRODUCT_SAVE")
                        .anyRequest().authenticated())
                // 添加了这个异常后，将无法再访问登录页面。
//                .exceptionHandling(exception -> exception.authenticationEntryPoint(myAuthenticationEntryPoint))

                .formLogin(withDefaults());
        return http.build();
    }


    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
